package com.example.calendar.data.local.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.example.calendar.data.model.CalendarEvent
import kotlinx.coroutines.flow.Flow
import org.threeten.bp.LocalDateTime

@Dao
interface EventDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertEvent(event: CalendarEvent): Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertEvents(events: List<CalendarEvent>): List<Long>

    @Update
    suspend fun updateEvent(event: CalendarEvent)

    @Delete
    suspend fun deleteEvent(event: CalendarEvent)

    @Query("UPDATE events SET isDeleted = 1, updatedAt = :now WHERE id = :eventId")
    suspend fun softDeleteEvent(eventId: String, now: LocalDateTime = LocalDateTime.now())

    @Query("SELECT * FROM events WHERE id = :eventId AND isDeleted = 0")
    fun getEventById(eventId: String): Flow<CalendarEvent?>

    @Query("SELECT * FROM events WHERE isDeleted = 0 ORDER BY startDateTime ASC")
    fun getAllEvents(): Flow<List<CalendarEvent>>

    @Query("SELECT * FROM events WHERE isDeleted = 0 AND isAllDay = :isAllDay ORDER BY startDateTime ASC")
    fun getAllDayEvents(isAllDay: Boolean = true): Flow<List<CalendarEvent>>

    @Transaction
    @Query("SELECT * FROM events WHERE isDeleted = 0 AND (startDateTime BETWEEN :start AND :end OR endDateTime BETWEEN :start AND :end OR (startDateTime <= :start AND endDateTime >= :end)) ORDER BY startDateTime ASC")
    fun getEventsBetweenDates(start: LocalDateTime, end: LocalDateTime): Flow<List<CalendarEvent>>

    @Query("SELECT * FROM events WHERE isDeleted = 0 AND DATE(startDateTime) = DATE(:date) OR DATE(endDateTime) = DATE(:date) ORDER BY startDateTime ASC")
    fun getEventsForDate(date: LocalDateTime): Flow<List<CalendarEvent>>

    @Query("SELECT * FROM events WHERE isDeleted = 0 AND categoryId = :categoryId ORDER BY startDateTime ASC")
    fun getEventsByCategory(categoryId: String): Flow<List<CalendarEvent>>

    @Query("SELECT * FROM events WHERE isDeleted = 0 AND (title LIKE '%' || :query || '%' OR description LIKE '%' || :query || '%' OR location LIKE '%' || :query || '%') ORDER BY startDateTime ASC")
    fun searchEvents(query: String): Flow<List<CalendarEvent>>

    @Query("SELECT COUNT(*) FROM events WHERE isDeleted = 0 AND DATE(startDateTime) = DATE(:date)")
    fun getEventCountForDate(date: LocalDateTime): Flow<Int>
} 